﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: Badanin M.V.
 * Дата: 24.06.2013
 * Время: 17:26
 * Проект: РПН Регион 2013
 * Распространяется под лицензией GPL v3
 */
using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
namespace Region
{
  /// <summary>
  /// Description of Auto.
  /// </summary>
  [DBObject(Table = "auto", PrimaryKeyPole = "AutoID")]
  public class Auto : DBObject
  {    
      #region Поля Заявки
      [DBColumn] public Int32 AutoID { get; set; }
      [DBColumn] public Int32 TimeStart { get; set; }
      [DBColumn] public Int32 TimeEnd { get; set; }
      [DBColumn] public Int32 DriverID { get; set; }
      [DBColumn] public Int32 PodpisUserID { get; set; }
      [DBColumn] public Int32 NachUserID { get; set; }
      [DBColumn] public DateTime Day { get; set; }
      [DBColumn] public String Address { get; set; }
      #endregion
      #region Переопределённые методы DBObject
      public override bool isEdit()
      {
        return base.isEdit();
      }      
      public override bool poleCheck(String PoleName, Object Value) { return true; }
      public override bool poleAccess(String PoleName)
      {
          return false;//Нет явынх править занчит надо запретить            
      }
      #endregion
      public Auto(Engine engine, Int32 AutoID)
          : base(engine, AutoID)
      {

      }
      public override void showEditor()
      {
/*          var F = new Forms.RasporForm(m_engine, AutoID);
          F.ShowDialog();*/
      }
  }
  public class AutoList
  {
    public class Line
    {
      public Int32 AutoID;
      public Int32 TimeStart;
      public Int32 TimeEnd;
      public Int32 DriverID;
      public Int32 UserID;
      public String UserFIO;
      public Int32 PodpisUserID;
      public Int32 NachUserID;
      public DateTime Day;
      public String Address;
    }    
    private Engine m_engine;
    private List<Line> m_lines;
    private Dictionary<String, Object> m_wheres;
    public Line getLine(Int32 l) { return this.m_lines[l]; }
    public Int32 NumLines { get { return m_lines.Count; } }
    private Int32 m_FullLines;
    public Int32 FullLines { get { return m_FullLines; } }    
    //Кеш списка отделов
    Dictionary<Int32, Dictionary<Int32, String>> m_UserList = new Dictionary<Int32, Dictionary<Int32, String>>();
    /// <summary>
    /// Возвращает список исполнителей у которых есть хотяб одно распоряжение
    /// </summary>
    /// <param name="IspUserFIO">Список фамилий</param>
    /// <param name="IspUserID">Список идентификаторов</param>        
    public Dictionary<Int32,String> UserList( Int32 ParentOtdelID)
    {
        if (m_UserList.ContainsKey(ParentOtdelID)) return m_UserList[ParentOtdelID];
        List<String> FIO = new List<String>();
        List<Int32> ID = new List<Int32>();
         Dictionary<Int32,String> R = new Dictionary<int,string>();
        SQLResult r = m_engine.SQLSelect(@"
SELECT auto.UserID, FIO 
FROM auto 
LEFT JOIN users ON users.UserID = auto.UserID 
INNER JOIN otdel_otdel ON otdel_otdel.OtdelID=users.OtdelID
WHERE  otdel_otdel.ParentOtdelID=@ParentOtdelID
GROUP BY auto.UserID", new SQLParam() { { "@ParentOtdelID", ParentOtdelID } });
        for (int i = 0; i < r.Count; i++) R[(Int32)r[i]["UserID"]] = (String)r[i]["FIO"];
        m_UserList[ParentOtdelID] = R;
        return R;
    }
      public AutoList(Engine engine)
      {
          m_engine = engine;
          m_lines = new List<Line>();
          m_wheres = new Dictionary<String, Object>();
      }
      public bool clearWhere()
      {
          m_wheres = new Dictionary<String, Object>();
          return true;
      }
      public bool setWhere(String Where, Object Value)
      {
          m_wheres[Where] = Value;
          return true;
      }
      public bool Filter()
      {
          List<String> Tables = new List<String>();
          List<String> Poles = new List<String>();
          List<String> Wheres = new List<String>();
          List<String> OrderBy = new List<String>();
          String OrderBySQL="",LimitSQL="";
          SQLParam Params = new SQLParam();
          //Params["@Param"]=100;
          Poles.Add("auto.AutoID");
          Poles.Add("auto.TimeStart");
          Poles.Add("auto.TimeEnd");
          Poles.Add("auto.DriverID");
          Poles.Add("auto.UserID");
          Poles.Add("auto.PodpisUserID");
          Poles.Add("auto.NachUserID");
          Poles.Add("auto.Day");
          Poles.Add("users.FIO as UserFIO");
          Poles.Add("auto.Address");          
                    
          Tables.Add("auto");          
          Tables.Add("LEFT JOIN users ON users.UserID=auto.UserID");
          Wheres.Add("1");
          OrderBy.Add("auto.AutoID DESC");

          if (m_wheres.ContainsKey("Day") && m_wheres["Day"] is DateTime)
          {
              Wheres.Add("auto.Day=@Day");
              Params["@Day"] =((DateTime)m_wheres["Day"]).Date;
          }
          if (OrderBy.Count > 0) OrderBySQL = "ORDER BY " + String.Join(", ", OrderBy.ToArray());
          String SQL = String.Format("SELECT {0} FROM {1} WHERE ({2}) {3} {4}",
              String.Join(", ", Poles.ToArray()),
              String.Join(" ", Tables.ToArray()),
              String.Join(") AND (", Wheres.ToArray()),
              OrderBySQL, LimitSQL);
          SQLResult r = m_engine.SQLSelect(SQL,Params);
          m_lines.Clear();
          for (Int32 i = 0; i < r.Count; i++)            
          {
              Line l = new Line();
              l.AutoID = (Int32)r[i]["AutoID"];
              l.TimeStart = (Int32)r[i]["TimeStart"];
              l.TimeEnd = (Int32)r[i]["TimeEnd"];
              l.DriverID = (Int32)r[i]["DriverID"];
              l.UserID = (Int32)r[i]["UserID"];
              l.UserFIO = (String)r[i]["UserFIO"];
              l.PodpisUserID = (Int32)r[i]["PodpisUserID"];
              l.NachUserID = (Int32)r[i]["NachUserID"];
              l.Day = (RegionDate)r[i]["Day"];
              l.Address = (String)r[i]["Address"];             
              m_lines.Add(l);
          }
          return true;
      }
  }
  public partial class Engine
  {
      /// <summary> Список открытых распояжений </summary>
      private Dictionary<Int32, Auto> l_Auto;
      /// <summary> Получить распоряжение по его идентификатору</summary><param name="RasporID">ИД Распоряжения</param><returns>Объект распоряжения</returns>
      public Auto getAuto(Int32 AutoID)
      {
          if (l_Auto == null) l_Auto = new Dictionary<Int32, Auto>();
          if (l_Auto.ContainsKey(AutoID)) return (Auto)l_Auto[AutoID];
          Auto auto = new Auto(this, AutoID);
          l_Auto[AutoID] = auto;
          return auto;
      }
      /// <summary>Создать новую заявку</summary><returns>Идентификатор новой заявки</returns>
      public Int32 newAuto(DateTime Day,Int32 TimeStart,Int32 TimeEnd, Int32 DriverID,Int32 UserID,String Address)
      {
          SQLParam Param = new SQLParam();
          Param["@Day"] = Day;
          Param["@TimeStart"] = TimeStart;
          Param["@TimeEnd"] = TimeEnd;
          Param["@DriverID"] = DriverID;
          Param["@UserID"] = UserID;
          Param["@Address"] = Address;
          MySqlCommand cmd;
          SQLEdit(@"INSERT INTO auto(Day,TimeStart,TimeEnd,DriverID,UserID,Address) VALUES (@Day,@TimeStart,@TimeEnd,@DriverID,@UserID,@Address)", Param, out cmd);
          return (Int32)cmd.LastInsertedId;
      }
      public bool delAuto(Int32 AutoID)
      {
          if (!CurrentUser.isAccess("Admin")) return false;//нельзя удалить черновик другово отдела
          SQLParam Param = new SQLParam();
          Param["AutoID"] = AutoID;
          //Удалить
          Int32 N = SQLEdit("DELETE FROM auto WHERE AutoID=@AutoID", Param);
          if (N == 1) return true;
          return false;
      }
  }
  
}
